package com.example.elm.First_Page;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.elm.Login.Login_Page;
import com.example.elm.R;
import com.example.elm.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Setting_Page extends Fragment {

    View root;

    boolean is_loading_data = false, is_login = false;

    private class Loading_Is_Login_Thread extends Thread {
        @Override
        public void run() {
            is_loading_data = false;
            is_login = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM user WHERE android_id = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID));
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        is_login = true;
                    }
                    is_loading_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!is_login) {
                        Intent intent = new Intent(root.getContext(), Login_Page.class);
                        startActivity(intent);
                    }
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_setting__page, container, false);

        Loading_Is_Login_Thread loadingIsLoginThread = new Loading_Is_Login_Thread();
        loadingIsLoginThread.start();

        return root;
    }
}